package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.vrv.app.cyberspace.common.utils.HttpContextUtils;
import com.vrv.app.cyberspace.common.utils.JSONResult;
import com.vrv.app.cyberspace.modules.sys.entity.*;
import com.vrv.app.cyberspace.modules.sys.mapper.*;
import com.vrv.app.cyberspace.modules.sys.service.IBaseTableService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.vrv.app.cyberspace.common.utils.JSONResult.renderError;
import static com.vrv.app.cyberspace.common.utils.JSONResult.renderSuccess;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sm
 * @since 2017-12-15
 */
@SuppressWarnings({"SpringJavaInjectionPointsAutowiringInspection", "Duplicates"})
@Service
@Transactional
public class BaseTableServiceImpl extends ServiceImpl<BaseTableMapper, BaseTable> implements IBaseTableService {
    Logger logger = LoggerFactory.getLogger(RiskTableServiceImpl.class);

    @Autowired
    private BaseTableMapper baseTableMapper;
    @Autowired
    private InformationTableMapper informationTableMapper;
    @Autowired
    private EventTableMapper eventTableMapper;
    @Autowired
    private RiskTableMapper riskTableMapper;
    @Autowired
    private InformationTypeTableMapper informationTypeTableMapper;
    @Autowired
    private IndustryTableMapper industryTableMapper;
    @Autowired
    private RegionTableMapper regionTableMapper;
    @Autowired
    private InfrastructureInformationTableMapper infrastructureInformationTableMapper;
    @Autowired
    private UserTableMapper userTableMapper;
    @Autowired
    private RiskTypeTableMapper riskTypeTableMapper;
    @Autowired
    private EventTypeTableMapper eventTypeTableMapper;
    @Autowired
    private RoleTableMapper roleTableMapper;
    @Autowired
    private TodayBulletinTableMapper todayBulletinTableMapper;
    @Autowired
    private FeedbackTableMapper feedbackTableMapper;
    @Autowired
    private AttachmentTableMapper attachmentTableMapper;
    @Autowired
    private EventFeedbackTableMapper eventFeedbackTableMapper;
    @Autowired
    private RiskFeedbackTableMapper riskFeedbackTableMapper;
    @Autowired
    private RiskManageTableMapper riskManageTableMapper;
    @Autowired
    private EventManageTableMapper eventManageTableMapper;

    @Override
    public JSONResult getListBase(Page<BaseTable> page, String startTime, String endTime, String title, Integer type) {
        EntityWrapper<BaseTable> ew = new EntityWrapper<>();
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        RoleTable roleTable = roleTableMapper.selectById(userTable.getRoleID());
        if (roleTable.getRoleType().equals("ROLE_DUTY")) {
            ew.eq("isEnabled", 1);
        } else {
            ew.eq("createUserID", userTable.getLinkdoodID());
        }
        if (type != null) {
            ew.eq("infoType", type);
        }
        if (StringUtils.isNotEmpty(title)) {
            ew.like("title", title);
        }
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            ew.between("createTime",startTime+" 00:00:00",endTime+" 23:59:59");
        }
        ew.orderBy("createTime", false);
        List<BaseTable> bts = baseTableMapper.selectPage(page, ew);
        if (type != null) {
            switch (type) {
                case 1:
                    for (BaseTable bt : bts) {
                        bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
                        InformationTable it = informationTableMapper.selectById(bt.getId());
                        List<InformationTypeTable> informationTypeList = informationTypeTableMapper.selectList(new EntityWrapper<InformationTypeTable>().in("id", it.getType().split(",")));
                        if (CollectionUtils.isNotEmpty(informationTypeList)) {
                            List<String> informationTypeListString = new ArrayList<>();
                            for (InformationTypeTable itt :
                                    informationTypeList) {
                                informationTypeListString.add(itt.getName());
                            }
                            it.setInformationTypeListString(StringUtils.join(informationTypeListString, ","));
                        }
                        bt.setExtend(it);
                    }
                    break;
                case 2:
                    for (BaseTable bt : bts) {
                        bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
                        RiskTable rt = riskTableMapper.selectById(bt.getId());
                        RiskTypeTable riskType = riskTypeTableMapper.selectById(rt.getPrimaryRiskType());
                        rt.setRiskType(riskType);
                        bt.setExtend(rt);
                    }
                    break;
                case 3:
                    for (BaseTable bt : bts) {
                        bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
                        EventTable et = eventTableMapper.selectById(bt.getId());
                        et.setFirstEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeFirst()));
                        et.setSecondEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeSecond()));
                        bt.setExtend(et);
                    }
                    break;
            }
        } else {
            for (BaseTable bt : bts) {
                bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
                if (bt.getInfoType() == 1) {
                    InformationTable it = informationTableMapper.selectById(bt.getId());
                    List<InformationTypeTable> informationTypeList = informationTypeTableMapper.selectList(new EntityWrapper<InformationTypeTable>().in("id", it.getType().split(",")));
                    if (CollectionUtils.isNotEmpty(informationTypeList)) {
                        List<String> informationTypeListString = new ArrayList<>();
                        for (InformationTypeTable itt :
                                informationTypeList) {
                            informationTypeListString.add(itt.getName());
                        }
                        it.setInformationTypeListString(StringUtils.join(informationTypeListString, ","));
                    }
                    bt.setExtend(it);
                } else if (bt.getInfoType() == 2) {
                    bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
                    RiskTable rt = riskTableMapper.selectById(bt.getId());
                    bt.setExtend(rt);
                } else if (bt.getInfoType() == 3) {
                    bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
                    EventTable et = eventTableMapper.selectById(bt.getId());
                    et.setFirstEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeFirst()));
                    et.setSecondEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeSecond()));
                    bt.setExtend(et);
                }
            }
        }
        page.setRecords(bts);
        return renderSuccess(page);
    }

    @Override
    public JSONResult getBase(Integer id) {
        BaseTable bt = baseTableMapper.selectById(id);
        if (bt == null) {
            return renderError("信息不存在！");
        }
        bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
        if (bt.getInfoType() == 1) {//信息
            InformationTable it = informationTableMapper.selectById(id);
            List<InformationTypeTable> informationTypeList = informationTypeTableMapper.selectList(new EntityWrapper<InformationTypeTable>().in("id", it.getType().split(",")));
            List<String> informationTypeListString = new ArrayList<>();
            for (InformationTypeTable itt : informationTypeList) {
                informationTypeListString.add(itt.getName());
            }
            it.setInformationTypeListString(StringUtils.join(informationTypeListString, ","));
            it.setInformationTypeList(informationTypeList);
            bt.setExtend(it);
        } else if (bt.getInfoType() == 2) {//风险
            RiskTable rt = riskTableMapper.selectById(id);
            String[] attIDs = StringUtils.isNotEmpty(rt.getEnclosure()) ? rt.getEnclosure().split(",") : new String[0];
            List<AttachmentTable> attachmentList = new ArrayList<>();
            for (String attID : attIDs) {
                attachmentList.add(attachmentTableMapper.selectById(attID));
            }
            rt.setAttachmentList(attachmentList);
            RiskTypeTable riskType = riskTypeTableMapper.selectById(rt.getPrimaryRiskType());
            rt.setRiskType(riskType);
            List<IndustryTable> industryList = industryTableMapper.selectList(new EntityWrapper<IndustryTable>().in("id", rt.getIndustryIDs().split(",")));
            if (CollectionUtils.isNotEmpty(industryList)) {
                List<String> industryListString = new ArrayList<>();
                for (IndustryTable it : industryList) {
                    industryListString.add(it.getName());
                }
                rt.setIndustryListString(StringUtils.join(industryListString, ","));
            }
            rt.setIndustryList(industryList);
            List<RegionTable> regionList = regionTableMapper.selectList(new EntityWrapper<RegionTable>().in("id", rt.getRegionIDs().split(",")));
            if (CollectionUtils.isNotEmpty(regionList)) {
                List<String> regionListString = new ArrayList<>();
                for (RegionTable rrt : regionList) {
                    regionListString.add(rrt.getName());
                }
                rt.setRegionListString(StringUtils.join(regionListString, ","));
            }
            rt.setRegionList(regionList);
            if (StringUtils.isNotEmpty(rt.getInfrastructureIDs())) {
                List<InfrastructureInformationTable> iits = new ArrayList<>();
                for (String InfrastructureInformationID : rt.getInfrastructureIDs().split(",")) {
                    InfrastructureInformationTable iit = infrastructureInformationTableMapper.selectById(InfrastructureInformationID);
                    iits.add(iit);
                }
                rt.setInfrastructureList(iits);
            }
            bt.setExtend(rt);
        } else if (bt.getInfoType() == 3) {//事件
            EventTable et = eventTableMapper.selectById(id);
            String[] attIDs = StringUtils.isNotEmpty(et.getEnclosure()) ? et.getEnclosure().split(",") : new String[0];
            List<AttachmentTable> attachmentList = new ArrayList<>();
            for (String attID : attIDs) {
                attachmentList.add(attachmentTableMapper.selectById(attID));
            }
            et.setAttachmentList(attachmentList);
            et.setFirstEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeFirst()));
            et.setSecondEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeSecond()));
            List<IndustryTable> industryList = industryTableMapper.selectList(new EntityWrapper<IndustryTable>().in("id", et.getIndustryIDs().split(",")));
            if (CollectionUtils.isNotEmpty(industryList)) {
                List<String> industryListString = new ArrayList<>();
                for (IndustryTable it : industryList) {
                    industryListString.add(it.getName());
                }
                et.setIndustryListString(StringUtils.join(industryListString, ","));
            }
            et.setIndustryList(industryList);
            List<RegionTable> regionList = regionTableMapper.selectList(new EntityWrapper<RegionTable>().in("id", et.getRegionIDs().split(",")));
            if (CollectionUtils.isNotEmpty(regionList)) {
                List<String> regionListString = new ArrayList<>();
                for (RegionTable rrt : regionList) {
                    regionListString.add(rrt.getName());
                }
                et.setRegionListString(StringUtils.join(regionListString, ","));
            }
            et.setRegionList(regionList);
            if (StringUtils.isNotEmpty(et.getInfrastructureIDs())) {
                List<InfrastructureInformationTable> iits = new ArrayList<>();
                for (String InfrastructureInformationID : et.getInfrastructureIDs().split(",")) {
                    InfrastructureInformationTable iit = infrastructureInformationTableMapper.selectById(InfrastructureInformationID);
                    iits.add(iit);
                }
                et.setInfrastructureList(iits);
            }
            bt.setExtend(et);
        }
        return renderSuccess(bt);
    }

    @Override
    public JSONResult getDynamicInformationList(Page<BaseTable> page) {
        EntityWrapper<BaseTable> ew = new EntityWrapper<>();
        ew.eq("TODAY_BULLETIN_TABLE.`status`", 3);
        ew.orderBy("bt.updateTime", false);
        List<BaseTable> bts = baseTableMapper.selectDynamicInformationList(page, ew);
        for (BaseTable bt : bts) {
            bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
            switch (bt.getInfoType()) {
                case 1:
                    InformationTable it = informationTableMapper.selectById(bt.getId());
                    List<InformationTypeTable> informationTypeList = informationTypeTableMapper.selectList(new EntityWrapper<InformationTypeTable>().in("id", it.getType().split(",")));
                    if (CollectionUtils.isNotEmpty(informationTypeList)) {
                        List<String> informationTypeListString = new ArrayList<>();
                        for (InformationTypeTable itt :
                                informationTypeList) {
                            informationTypeListString.add(itt.getName());
                        }
                        it.setInformationTypeListString(StringUtils.join(informationTypeListString, ","));
                    }
                    bt.setExtend(it);
                    break;
                case 2:
                    RiskTable rt = riskTableMapper.selectById(bt.getId());
                    RiskTypeTable riskType = riskTypeTableMapper.selectById(rt.getPrimaryRiskType());
                    rt.setRiskType(riskType);
                    bt.setExtend(rt);
                    break;
                case 3:
                    EventTable et = eventTableMapper.selectById(bt.getId());
                    et.setFirstEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeFirst()));
                    et.setSecondEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeSecond()));
                    bt.setExtend(et);
                    break;
            }
        }
        page.setRecords(bts);
        return renderSuccess(page);
    }

    @Override
    public JSONResult getListHistory(Page<BaseTable> page, String startTime, String endTime, String title, Integer isEnabled, Integer type) {
        EntityWrapper<BaseTable> ew = new EntityWrapper<>();
        if (isEnabled == 1) {
            ew.eq("isEnabled", 2);
            ew.eq("tbt.status", 3);
        } else if (isEnabled == 2) {
            ew.eq("isEnabled", 3);
        }
        ew.eq("infoType", type);
        ew.like("title", title);
        ew.orderBy("createTime", true);
        List<BaseTable> bts = baseTableMapper.selectListHistory(page, ew);
        switch (type) {
            case 1:
                for (BaseTable bt : bts) {
                    bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
                    InformationTable it = informationTableMapper.selectById(bt.getId());
                    List<InformationTypeTable> informationTypeList = informationTypeTableMapper.selectList(new EntityWrapper<InformationTypeTable>().in("id", it.getType().split(",")));
                    List<String> informationTypeListString = new ArrayList<>();
                    for (InformationTypeTable itt :
                            informationTypeList) {
                        informationTypeListString.add(itt.getName());
                    }
                    it.setInformationTypeListString(StringUtils.join(informationTypeListString, ","));
                    bt.setExtend(it);
                }
                break;
            case 2:
                for (BaseTable bt : bts) {
                    bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
                    RiskTable rt = riskTableMapper.selectById(bt.getId());
                    RiskTypeTable riskType = riskTypeTableMapper.selectById(rt.getPrimaryRiskType());
                    rt.setRiskType(riskType);
                    bt.setExtend(rt);
                }
                break;
            case 3:
                for (BaseTable bt : bts) {
                    bt.setCreateUserInfo(userTableMapper.selectById(bt.getCreateUserID()));
                    EventTable et = eventTableMapper.selectById(bt.getId());
                    et.setFirstEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeFirst()));
                    et.setSecondEventType(eventTypeTableMapper.selectById(et.getPrimaryEventTypeSecond()));
                    bt.setExtend(et);
                }
                break;
        }
        page.setRecords(bts);
        return renderSuccess(page);
    }

    @Override
    public JSONResult dataCount() {
        UserTable userTable = (UserTable) HttpContextUtils.getHttpServletRequest().getSession().getAttribute("user");
        if (userTable == null) {
            return renderError("操作被禁止，会话超时，重启豆豆浏览器！");
        }
        JSONObject jsonObject = new JSONObject();
        JSONObject warningCount = new JSONObject();
        warningCount.put("red", riskManageTableMapper.selectCount(new EntityWrapper<RiskManageTable>().eq("warningLevel", 1).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        warningCount.put("orange", riskManageTableMapper.selectCount(new EntityWrapper<RiskManageTable>().eq("warningLevel", 2).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        warningCount.put("yellow", riskManageTableMapper.selectCount(new EntityWrapper<RiskManageTable>().eq("warningLevel", 3).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        warningCount.put("blue", riskManageTableMapper.selectCount(new EntityWrapper<RiskManageTable>().eq("warningLevel", 4).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        warningCount.put("none", riskManageTableMapper.selectCount(new EntityWrapper<RiskManageTable>().eq("warningLevel", 0).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        jsonObject.put("warningCount", warningCount);
        JSONObject eventCount = new JSONObject();
        eventCount.put("level1", eventManageTableMapper.selectCount(new EntityWrapper<EventManageTable>().eq("primaryEventGrade", 1).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        eventCount.put("level2", eventManageTableMapper.selectCount(new EntityWrapper<EventManageTable>().eq("primaryEventGrade", 2).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        eventCount.put("level3", eventManageTableMapper.selectCount(new EntityWrapper<EventManageTable>().eq("primaryEventGrade", 3).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        eventCount.put("level4", eventManageTableMapper.selectCount(new EntityWrapper<EventManageTable>().eq("primaryEventGrade", 4).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        eventCount.put("level5", eventManageTableMapper.selectCount(new EntityWrapper<EventManageTable>().eq("primaryEventGrade", 5).eq("approvalUserID", userTable.getLinkdoodID()).and("status!=7")));
        jsonObject.put("eventCount", eventCount);
        JSONObject taskCount = new JSONObject();
        taskCount.put("riskNum", riskManageTableMapper.selectCount(new EntityWrapper<RiskManageTable>().and("status!=7").eq("approvalUserID", userTable.getLinkdoodID())));
        taskCount.put("eventNum", eventManageTableMapper.selectCount(new EntityWrapper<EventManageTable>().and("status!=7").eq("approvalUserID", userTable.getLinkdoodID())));
        taskCount.put("todayBulletinNum", todayBulletinTableMapper.selectCount(new EntityWrapper<TodayBulletinTable>().and("status!=3").eq("approvalUserID", userTable.getLinkdoodID())));
        jsonObject.put("taskCount", taskCount);
        //每日零报告
        Wrapper<FeedbackTable> ewf = new EntityWrapper<FeedbackTable>().eq("feedbackOrgID", userTable.getOrgID()).eq("isSubmit", 0);
        jsonObject.put("dailyReportNum", feedbackTableMapper.selectCount(ewf));
        //我的任务-事件
        Wrapper<EventFeedbackTable> eft = new EntityWrapper<EventFeedbackTable>().eq("orgID", userTable.getOrgID()).eq("status", 0);
        jsonObject.put("eventMyTaskNum", eventFeedbackTableMapper.selectCount(eft));
        //我的任务-预警
        Wrapper<RiskFeedbackTable> rft = new EntityWrapper<RiskFeedbackTable>().eq("orgID", userTable.getOrgID()).eq("status", 0);
        jsonObject.put("riskMyTaskNum", riskFeedbackTableMapper.selectCount(rft));
        return renderSuccess(jsonObject);
    }
}
